define(["moment", 'module/system/program/update/update'], function (moment) {
    return ["$rootScope", "$scope", "$filter", "$stateParams", "$translate", "$mdDialog", "config", "$locale", "MMWService",
    'RouterExtendProvider', 'CommonService', 'HttpService',
    function ($rootScope, $scope, $filter, $stateParams, $translate, $mdDialog, config, $locale, $MMWService,
        $RouterExtendProvider, $CommonService, $HttpService) {
        $scope.parent = $stateParams.parent;
        var defaultUse = $scope.currentUse = $translate.use(), defaultServer;
        $scope.langList = [];
        $scope.device = config.cache.device;
        $scope.init = function(){
            try{
                $scope.$root.hideMenu();
            }catch(e){}
            var temp = config.server.ip.split('.');
            if(temp.length != 4){
                $scope.serverIp = ["0", "0", "0", "0"];
            } else {
                $scope.serverIp = temp;
            }

            $scope.config = angular.merge({}, config);//copy
            defaultServer  = angular.merge({}, config.server);//copy

            if(config.langList){
                config.langList.forEach(function(lang){
                    $scope.langList.push({code:lang, label:$filter('translate')('Setting.'+lang)});
                });
            } else {
                $scope.langList = [
                    {code:'zh_TW',label:$filter('translate')('Setting.zh_TW')},
                    {code:'zh_CN',label:$filter('translate')('Setting.zh_CN')},
                    {code:'en_US',label:$filter('translate')('Setting.en_US')}
                ];
            }

            if(!window.cordova && !window.nodeRequire){
                $scope.debug = true;
            } else if(window.nodeRequire){
                $scope.isElectron = true;
            } else if(window.cordova){
                $scope.isCordova = true;
            }
        };

        $scope.back = function(){
            if($stateParams.sideMenu == true)
                $RouterExtendProvider.triggerSetting();
            else
                $scope.$root.changeProgram($scope.parent, true);
        };

        $scope.final = function(callback){
            if(defaultUse!=$scope.currentUse){
                $scope.$root.lang = $scope.currentUse = defaultUse;
                $translate.use(defaultUse);
            }
            if(typeof callback === 'function')
                callback();
        };

        $scope.confirm = function(feedback){
            if($scope.config.setting.RefreshTime <= 0 ){
                $scope.$root.showAlert($filter('translate')('Setting.msg.RefreshTimeZero'));
                return;
            }

            //config = $scope.config;
            config.server = $scope.config.server;
            config.server.ip = combineIP($scope.serverIp);

            //config.client.ip = combineIP($scope.clientIp);
            //config.client.mask = combineIP($scope.clientMask);
            //config.client.gateway = combineIP($scope.clientGateway);
            if($RouterExtendProvider.NotificationHub)
                if(config.setting.OperatingArea != $scope.config.setting.OperatingArea)
                    $RouterExtendProvider.ChangeGroup(config.setting.OperatingArea, $scope.config.setting.OperatingArea);
                    
            config.setting = $scope.config.setting;
            defaultUse = config.setting.lang = $scope.currentUse;

            if (typeof(Storage) !== "undefined") {
                localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
                localStorage.setItem(config.appName + "_setting", JSON.stringify(config.setting));
                //localStorage.setItem(config.appName + "_lang", $scope.currentUse);
              
            }

            fullScreen();
            
            const callback = () => {
                if (feedback) {
                    feedback();
                } else {
                    if ($stateParams.sideMenu == true)
                        $RouterExtendProvider.triggerSetting();
                    else
                        $scope.$root.changeProgram($scope.parent, true);
                }
            };

            // 20231211 modify by Alan for#152659: 修正平台菜單更新邏輯
            // 非登入狀態不更新menu，手機版走舊版菜單設定
            if ($scope.parent === 'login' || config.cache.device === 'phone') {
                callback();
                return;
            }



            dynamic_menu_info_get(function (data) {
                var menu = data.filter(menu => {
                    // 自定义报表會跳提示訊息，所以不關
                    if (menu.name === 'modelC') {
                        return true;
                    } else if (menu.platform === 'Pad' && menu.menus.length != 0) {
                        return true;
                    }
                });
                var menuFormat = menuParser(menu, config.oriMenu);
                if(config.cache.permissions){
                    checkPermissions(menuFormat, config.cache.permissions);
                 }     
                // 20231115 modify by Alan for#0149444 : 更新菜單上的自定義報表
                updateMenu(menuFormat, () => {
                    config.menu = angular.merge([], menu);
                    // 20230314 modify by Alan for#130175: 修正選單取得邏輯
                    config.menu = checkSubMenu(config.menu);//處理特殊menu顯示
                    $rootScope.modules = $rootScope.menu = angular.merge([], config.menu);
                    callback()
                })
            });
        };

        // 20240320 add by shiwl for M# 0159533: 权限设置为派工作业和派工设定的同一个账号，只是刚登陆时没有下栏明细，点击设置后，就出来了，没改权限
         function checkPermissions(menu,permissions){
                var firstMenuItem;
                menu.forEach(function(menuItem){
                  if(menuItem.childs){
                      menuItem.childs.forEach(function (childItem) {
                        if (childItem.childs) {
                            var firstSubMenuItem;
                            childItem.childs.forEach(function (subChildItem) {
                                if (permissions.indexOf(subChildItem.name) != -1) {
                                    subChildItem.isShow = true && subChildItem.isShow;
                                    if (!firstSubMenuItem) {
                                        firstSubMenuItem = subChildItem;
                                    }
                                } else {
                                    subChildItem.isShow = false;
                                }
                            });
                        }
                   });
                  }
                });
               
         }

        function dynamic_menu_info_get(callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.dynamic_menu_info_get',
                success: function (data) {
                    if (typeof callback === 'function') {
                        callback(data);
                    }
                }
            });
        }

        // 解析menu轉為前端格式
        function menuParser(source, ori) {
            source.forEach(element => {
				//20221227 modify by Dustdusk for M#: 增加使用formName取代name
				element.name = element.formName||element.name;
                let menuListUpdated = false
				let oriElement = ori.find(_c => _c.name == element.name);
                // 當子選單為0時，把自己設為預設作業
                if(element.menus && element.menus.length === 0) {
                    element.default = element.name;
                }
                if(element.menus && element.menus.length > 0) {
                    
                    // 20230804 modify by wenwei for M#141874 於作業中更改語系，底下的controllbar 不會改變
                    if (!menuListUpdated && element.menus.some(item => item.name == $scope.parent)) {
                        $rootScope.menuList = element.menus
                        menuListUpdated = true
                    }
                    element.childs = element.menus;
                    delete element.menus;
                    element.childs = menuParser(element.childs, (oriElement||{}).childs||[]);
                }
                element.isShow = element.isShown === 'Y';
                element.title = element.displayText;
                element.icon = element.icon || 'W_Com_Report_nor_32';
                //element.icon_cli = element.icon_cli || 'W_Com_Report_sel_32';
				if(oriElement != undefined) {
				    element.tag = oriElement.tag;
				    element.isReport = oriElement.isReport;

					element.icon_cli = oriElement.icon_cli||element.icon;
					element.icon_s = oriElement.icon_s||element.icon;
					element.color = oriElement.color;
				} else {
					element.icon_cli = element.icon || 'W_Com_Report_sel_32';
				}
            });

            return source;
        }

        //處理subMenu顯示作業
        function checkSubMenu(Menu) {
            Menu.forEach(e => {
            //特殊處理
            switch (e.name) {
                case 'modelB':
                    if (window.cordova) {
                        //條碼標籤列印作業
                        e.childs = e.childs.filter(x => x.name !== 'modelB12')
                    }
                    break;

                default:
                    break;
            }
            });
            
            return Menu;
        }

        function combineIP(array){
            var totalip;
            array.forEach(function(ipstring){
                if(totalip == undefined)
                    totalip = ipstring;
                else
                    totalip += "." +ipstring;
            });
            return totalip;
        }

        //載入語系清單
        $scope.loadLoaclizationList = function(){
            $scope.$root.showSelect({
                title : $filter('translate')('Setting.localizationList'),
                label : 'label',
                code : 'code',
                selectCode : $scope.currentUse,
                list : $scope.langList,
                confirm : function(item, dialog){
                    $translate.use(item.code);
                    $locale.id = "en-US";
                    $scope.$root.lang = $scope.currentUse = item.code;
                    dialog.hide();
                }
            });
        };

        $scope.checkUpdate = function(){
            config.server = angular.merge({}, $scope.config.server);//copy
            config.server.ip = combineIP($scope.serverIp);
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.live_update',
                content : {
                    applicationId:config.applicationId
                },
                success : function(data){
                    config.server = angular.merge({}, defaultServer);//將底層的config 回復原本的內容
                    if(data.version == config.appVersion || data.version == '0.0.0.0'){
                        //不用更新
                        $scope.$root.showToast($filter('translate')('Setting.msg.dont_need.update').replace('{0}', config.appVersion));
                    } else {
                        //需要更新
                        $scope.$root.showConfirm($filter('translate')('Setting.msg.need.update').replace('{0}', data.version), function(){
                            $scope.confirm(function(){
                                if($scope.$root.isCordova){
                                    if(window.resolveLocalFileSystemURL){
                                        window.resolveLocalFileSystemURL(cordova.file.applicationDirectory+'www', function(app_root){
                                            window.location.href = app_root.toURL()+'/startup.html';
                                        }, function(){
                                            window.location.href = 'startup.html';
                                        });
                                    }
                                } else {
                                    window.location.href = 'startup.html';
                                }
                            });
                        });
                    }
                }
            });
        };

        $scope.changeVersion = function(){
            var temp_version = config.appVersion.match(/(.\..\.[^\.]+)/)[0].replace(/\./g, '');
            if(temp_version != '2010'){
                temp_version = '210';
            } else if(temp_version <= '209'){
                temp_version = '209';
            }
            $mdDialog.dialog(
                'module/system/program/setting/version_change.html',
                function(dialog){
                    return {
                        beforeShown:function(){
                            $CommonService.changeMode = function(){};
                            $CommonService.writeLog = function(msg){
                                $scope.$root.hideLoading();
                                $scope.$root.showAlert(msg);
                            };
                        },
                        version_arr:{'209':'2.0.9', '2010':'2.0.10', '210':'2.1.0'},
                        version:temp_version,
                        version_display:$filter('translate')('update.version.'+temp_version),
                        env : config.setting.environment,
                        env_display: $filter('translate')('Login.env.' + config.setting.environment),
                        view_mode : config.cache.device||'pad',
                        change_version:function(){
                            $scope.$root.showSelect({
                                title : $filter('translate')('Login.ServerList'),
                                label : 'label',
                                code : 'code',
                                selectCode : dialog.version,
                                list : [
                                    {label:$filter('translate')('update.version.209'), code:'209'},
                                    {label:$filter('translate')('update.version.2010'), code:'2010'},
                                    {label:$filter('translate')('update.version.210'), code:'210'},
                                ],
                                confirm : function(item, s_dialog){
                                    s_dialog.hide();
                                    dialog.version = item.code;
                                    dialog.version_display = item.label;
                                }
                            });
                        },
                        change_env:function(){
                            $scope.$root.showSelect({
                                title : $filter('translate')('Login.ServerList'),
                                label : 'label',
                                code : 'code',
                                selectCode : dialog.env,
                                list : [
                                    {label:$filter('translate')('Login.env.Production'), code:'Production'},
                                    {label:$filter('translate')('Login.env.Test'), code:'Test'},
                                ],
                                confirm : function(item, s_dialog){
                                    s_dialog.hide();
                                    dialog.env = item.code;
                                    dialog.env_display = item.label;
                                }
                            });
                        },
                        change_viewmode:function(mode){
                            dialog.view_mode = mode;
                        },
                        confirm:function(){
                            $scope.$root.showLoading();
                            $HttpService.send({
                                name:$CommonService.server_name[dialog.version][dialog.env],
                                ip: combineIP($scope.serverIp),
                                port: $scope.config.server.port,
                                version: dialog.version,
                                env: dialog.env,
                                content:{is_mobile:config.cache.device == 'phone'},
                                success:function(data){
                                    $scope.$root.hideLoading();
                                    $scope.$root.showConfirm($filter('translate')('Setting.version_change.warin', {version:data.version}), function(confirm_dialog){
                                        confirm_dialog.hide();
                                        $scope.config.setting.environment = dialog.env;
                                        $scope.confirm(function(){
                                            localStorage.setItem(config.appName + '_version', JSON.stringify({
                                                appVersion: dialog.version_arr[dialog.version]+'.00000000',
                                                module:[],
                                                isPhone:dialog.view_mode=='phone'?'Y':'N'
                                            }));

                                            dialog.hide();
                                            delete $CommonService.writeLog;
                                            delete $CommonService.changeMode;
                                            // 20220929 modify by Alan for#118600 : 取消resolveLocalFileSystemURL，產出來的URL在IOS上沒辦法跳轉
                                            window.location.href = 'startup.html';
                                        });
                                    });

                                }
                            });
                        },
                        back:function(){
                            dialog.hide();
                        }
                    };
                }
            );
        };

        $scope.changePassword = function(){
            $mdDialog.serviceDialog('PasswordService');
        };

        $scope.clickLang = function(item){
            $translate.use(item.code);
            $locale.id = 'en-US';
            $scope.$root.lang = $scope.currentUse = item.code;
        };

        $scope.showModuleVersion = function(){
            $scope.$root.showSelect({
                title : $filter('translate')('Setting.moduleVersion'),
                label : function(item){
                    return item.name + ' - '+item.version;
                },
                code : 'name',
                label_format:'',
                list : $scope.config.module,
                confirm : function(item, dialog){
                    dialog.hide();
                }
            });
        };

        $scope.showLogging = function(){
            $RouterExtendProvider.showLogging();
        };
        
        // 20220519 modify by Alan for#107965 : 登出按鈕搬遷至設定頁面
        $scope.logout = function(){
            $scope.$root.showConfirm($filter('translate')('home.msg.is_logout'),function(dialog){
                dialog.hide();
                $RouterExtendProvider.logout();
            });
        };

        // 20220411 modify by Alan for#110231 : 調整預設解析度
        function fullScreen(){
            if(window.nodeRequire){
                try{
                    // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                    const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                    var version = remote.app.getVersion();
                    if(version != '6.0.1'){
                        win = remote.getCurrentWindow();
                        if(config.setting.fullScreen == 'Y'){
                            win.setFullScreen(true);
                        } else {
                            win.width = 1140;
                            win.height = 660;
                            win.setFullScreen(false);
                        }
                    }
                }catch(e){
                    var win = nodeRequire('nw.gui').Window.get();
                    if(config.setting.fullScreen == 'Y'){
                        win.enterFullscreen();
                    } else {
                        win.leaveFullscreen();
                    }
                }
            }
        }

        // 管理看板
        function userKanbanManagementInfoGet(callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.user_kanban_management_info_get',
                content: {},
                success: function (data) {
                    if (typeof callback === 'function')
                        callback(data);
                }
            });
        }

        //使用者自訂報表
        function userCustomReportInfoGet(callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.user_custom_report_info_get',
                content: {},
                success: function (data) {
                    if (typeof callback === 'function')
                        callback(data);
                }
            });
        }

        // 20231115 modify by Alan for#0149444 : 更新module，，以菜單配置為準，若未配置菜單，則以自定義報表設定為準
        function updateModule({ menu, moduleName, rootName, service }, callback) {
            const moduleIndex = menu.findIndex(item => item.name === moduleName);
            if (moduleIndex != -1) {
                service((data) => {
                    if (data[rootName].length > 0) {
                        const childs = menu.find(item => item.name === moduleName).childs || [];
                        const reports = $filter('orderBy')(data[rootName], 'report_id');
                        const iconMap = {
                            'modelKB': 'W_Com_Board_nor_32',
                            'modelC': 'W_Com_User_Edit_nor_32'
                        }
                        const moduleKB = reports
                            .map((item, index) => {
                                let matchNode = childs.find(child => child.name === item.report_id)
                                return {
                                    name: item.report_id,
                                    displayText: matchNode ? matchNode.displayText : item.report_description,
                                    color: '#e6b800',
                                    icon: matchNode ? matchNode.icon : iconMap[moduleName],
                                    isShow: matchNode ? matchNode.isShow : true,
                                    order: matchNode ? matchNode.order : index,
                                    isReport: true
                                }
                            });
                        menu.find(item => item.name === moduleName).childs = moduleKB;
                    }
                    if (typeof callback === 'function') {
                        callback(menu);
                    }
                });
            } else {
                if (typeof callback === 'function') {
                    callback(menu);
                }
            }
        }

        // 20231115 modify by Alan for#0149444 : 更新menu
        function updateMenu(menu, callback) {
            const moduleKB = {
                menu: menu,
                moduleName: 'modelKB',
                rootName: 'kanban_management_info',
                service: userKanbanManagementInfoGet
            }
            updateModule(moduleKB, (menu) => {
                const moduleC = {
                    menu: menu,
                    moduleName: 'modelC',
                    rootName: 'report_info',
                    service: userCustomReportInfoGet
                }
                updateModule(moduleC, (menu) => {
                    if (typeof callback === 'function') {
                        callback(menu);
                    }
                })
            })
        }
        
        $scope.change = function(){
            // config.setting.fontSize = $scope.config.setting.fontSize;
            $scope.$root.fontSize = function () {
                // console.log(config.setting.fontSize);
                return { fontSize: `${ $scope.config.setting.fontSize }px` };
            }
        }

        $scope.fontPercentage = function () {
            if ($scope.config.setting.fontSize == undefined)
                $scope.config.setting.fontSize = 14
            return `${Math.floor($scope.config.setting.fontSize / 14 * 100)}%`;
        }

    }];
});
